<template>
  <div class="alert-management-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="page-title">预警管理</div>
      <el-button type="primary" @click="refreshAlerts">刷新数据</el-button>
    </div>

    <!-- 筛选区域 -->
    <el-card class="filter-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>查询条件</span>
          <div class="header-actions">
            <el-button size="small" @click="resetFilter">重置</el-button>
            <el-button size="small" type="primary" @click="handleFilter">查询</el-button>
          </div>
        </div>
      </template>
      <el-form :model="filterForm" :inline="true" class="filter-form">
        <el-form-item label="客户ID">
          <el-input v-model="filterForm.customerId" placeholder="请输入客户ID" clearable></el-input>
        </el-form-item>
        <el-form-item label="风险等级">
          <el-select v-model="filterForm.riskLevel" placeholder="全部" clearable>
            <el-option label="高风险" value="high"></el-option>
            <el-option label="中风险" value="medium"></el-option>
            <el-option label="低风险" value="low"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="处理状态">
          <el-select v-model="filterForm.status" placeholder="全部" clearable>
            <el-option label="待处理" value="pending"></el-option>
            <el-option label="处理中" value="processing"></el-option>
            <el-option label="已完成" value="completed"></el-option>
            <el-option label="已关闭" value="closed"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预警时间">
          <el-date-picker
            v-model="filterForm.timeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="负责人">
          <el-input v-model="filterForm.assignee" placeholder="请输入负责人" clearable></el-input>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <div class="stats-card-container">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="stats-card" shadow="hover">
            <div class="stats-card-content">
              <div class="stats-value">{{ statistics.totalAlerts }}</div>
              <div class="stats-label">预警总数</div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="stats-card stats-pending" shadow="hover">
            <div class="stats-card-content">
              <div class="stats-value">{{ statistics.pendingAlerts }}</div>
              <div class="stats-label">待处理预警</div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="stats-card stats-processing" shadow="hover">
            <div class="stats-card-content">
              <div class="stats-value">{{ statistics.processingAlerts }}</div>
              <div class="stats-label">处理中预警</div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="stats-card stats-completed" shadow="hover">
            <div class="stats-card-content">
              <div class="stats-value">{{ statistics.completedAlerts }}</div>
              <div class="stats-label">已完成预警</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 预警列表 -->
    <el-card class="alert-list-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>预警列表</span>
          <div class="header-actions">
            <el-button size="small" type="success" @click="batchProcess" :disabled="selectedRows.length === 0">批量处理</el-button>
            <el-button size="small" type="primary" @click="showCreateAlertDialog">新建预警</el-button>
          </div>
        </div>
      </template>

      <el-table
        ref="alertTable"
        v-loading="loading"
        :data="alertList"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="预警ID" width="80"></el-table-column>
        <el-table-column prop="customer_id" label="客户ID" width="120"></el-table-column>
        <el-table-column prop="customer_name" label="客户名称" width="100"></el-table-column>
        <el-table-column prop="risk_level" label="风险等级" width="100">
          <template #default="scope">
            <el-tag
              :type="scope.row.risk_level === 'high' ? 'danger' : scope.row.risk_level === 'medium' ? 'warning' : 'success'"
              effect="dark"
            >
              {{ scope.row.risk_level_display }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="probability" label="流失概率" width="100">
          <template #default="scope">
            {{ (scope.row.probability * 100).toFixed(2) }}%
          </template>
        </el-table-column>
        <el-table-column prop="main_factors" label="主要风险因素" show-overflow-tooltip></el-table-column>
        <el-table-column prop="created_at" label="预警时间" width="150">
          <template #default="scope">
            {{ formatDateTime(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column prop="assignee_name" label="负责人" width="100"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag
              :type="
                scope.row.status === 'pending' ? 'info' :
                scope.row.status === 'processing' ? 'warning' :
                scope.row.status === 'completed' ? 'success' : 'default'
              "
            >
              {{ scope.row.status_display }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="260" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="viewCustomerDetail(scope.row)">查看客户</el-button>
            <el-button
              size="small"
              type="primary"
              @click="processAlert(scope.row)"
              v-if="scope.row.status !== 'completed' && scope.row.status !== 'closed'"
            >
              {{ scope.row.status === 'pending' ? '处理' : '完成' }}
            </el-button>
            <el-button size="small" type="success" @click="viewRetentionPlan(scope.row)">挽留方案</el-button>
            <el-button size="small" type="danger" @click="closeAlert(scope.row)" v-if="scope.row.status !== 'closed'">关闭</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 处理预警对话框 -->
    <el-dialog :title="dialogTitle" v-model="processDialogVisible" width="500px">
      <el-form :model="processForm" label-width="80px">
        <el-form-item label="客户ID">
          <el-input v-model="processForm.customerId" disabled></el-input>
        </el-form-item>
        <el-form-item label="风险等级">
          <el-tag
            :type="processForm.riskLevel === 'high' ? 'danger' : processForm.riskLevel === 'medium' ? 'warning' : 'success'"
            effect="dark"
          >
            {{ processForm.riskLevelDisplay }}
          </el-tag>
        </el-form-item>
        <el-form-item label="负责人">
          <el-select v-model="processForm.assignee" placeholder="请选择负责人" style="width: 100%">
            <el-option 
              v-for="user in userList" 
              :key="user.id" 
              :label="user.full_name || user.username" 
              :value="user.id"
            >
              <div class="user-option">
                <div class="user-name">{{ user.full_name || user.username }}</div>
                <div class="user-info">
                  <span>{{ user.role_display || user.role }}</span>
                  <span v-if="user.department">· {{ user.department }}</span>
                </div>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="处理措施">
          <el-select v-model="processForm.actions" multiple placeholder="请选择处理措施" style="width: 100%">
            <el-option label="电话回访" value="call"></el-option>
            <el-option label="短信通知" value="sms"></el-option>
            <el-option label="邮件通知" value="email"></el-option>
            <el-option label="上门拜访" value="visit"></el-option>
            <el-option label="优惠活动" value="promotion"></el-option>
            <el-option label="服务升级" value="upgrade"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="处理备注">
          <el-input
            type="textarea"
            v-model="processForm.remarks"
            rows="4"
            placeholder="请输入处理备注信息"
          ></el-input>
        </el-form-item>
        <el-form-item label="预计完成" v-if="currentAlert.status === 'pending'">
          <el-date-picker
            v-model="processForm.expectedCompletionTime"
            type="date"
            placeholder="选择预计完成日期"
            style="width: 100%"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="是否挽留" v-if="currentAlert.status === 'processing'">
          <el-radio-group v-model="processForm.retained">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="processDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmProcess" :loading="processLoading">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 挽留方案对话框 -->
    <el-dialog title="挽留方案详情" v-model="retentionDialogVisible" width="600px">
      <div v-if="currentRetentionPlan">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="客户ID">{{ currentRetentionPlan.customer_id }}</el-descriptions-item>
          <el-descriptions-item label="客户名称">{{ currentRetentionPlan.customer_name }}</el-descriptions-item>
          <el-descriptions-item label="挽留状态">
            <el-tag :type="currentRetentionPlan.is_successful ? 'success' : 'danger'">
              {{ currentRetentionPlan.is_successful ? '已挽留' : '未挽留' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="负责人">{{ currentRetentionPlan.created_by_name }}</el-descriptions-item>
          <el-descriptions-item label="创建时间" :span="2">{{ formatDateTime(currentRetentionPlan.created_at) }}</el-descriptions-item>
          <el-descriptions-item label="挽留策略" :span="2">{{ currentRetentionPlan.strategy_display }}</el-descriptions-item>
          <el-descriptions-item label="详细描述" :span="2">{{ currentRetentionPlan.description }}</el-descriptions-item>
          <el-descriptions-item label="执行措施" :span="2">{{ formatActions(currentRetentionPlan.actions) }}</el-descriptions-item>
          <el-descriptions-item label="挽留备注" :span="2">{{ currentRetentionPlan.remarks }}</el-descriptions-item>
        </el-descriptions>
        
        <div class="retention-result" v-if="currentRetentionPlan.is_successful">
          <h4>挽留成果</h4>
          <div class="result-item">
            <div class="result-label">月均收入增加：</div>
            <div class="result-value">¥{{ currentRetentionPlan.income_increase }}</div>
          </div>
          <div class="result-item">
            <div class="result-label">预计客户价值：</div>
            <div class="result-value">¥{{ currentRetentionPlan.customer_value }}</div>
          </div>
          <div class="result-item">
            <div class="result-label">客户满意度：</div>
            <div class="result-value">{{ currentRetentionPlan.satisfaction }}/5</div>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="retentionDialogVisible = false">关 闭</el-button>
          <el-button type="primary" @click="editRetentionPlan" v-if="currentRetentionPlan">编辑方案</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 创建预警对话框 -->
    <el-dialog v-model="createDialogVisible" title="创建预警" width="500px">
      <el-form ref="createFormRef" :model="createForm" :rules="createFormRules" label-width="100px">
        <el-form-item label="客户" prop="customer_id">
          <div class="customer-select-container">
            <div class="customer-search-bar">
              <el-input 
                v-model="customerSearchQuery" 
                placeholder="搜索客户ID" 
                prefix-icon="el-icon-search" 
                clearable 
                @input="debounceCustomerSearch"
              ></el-input>
            </div>
          <el-select 
            v-model="createForm.customer_id" 
            filterable 
              remote
              :remote-method="remoteCustomerSearch"
              :loading="customerLoading"
            placeholder="选择高风险客户"
            style="width: 100%"
            @change="handleCustomerSelect"
              :filter-method="filterCustomers"
              popper-class="customer-select-dropdown"
          >
            <el-option
                v-for="customer in filteredCustomers"
              :key="customer.customer_id"
              :label="`${customer.customer_id} (${getRiskLevelText(customer.risk_level)}, ${(customer.probability * 100).toFixed(1)}%)`"
              :value="customer.customer_id"
            >
                <div class="customer-option">
                  <div class="customer-option-header">
                    <span class="customer-id">{{ customer.customer_id }}</span>
                  <el-tag :type="getRiskTagType(customer.risk_level)" size="small">
                    {{ getRiskLevelText(customer.risk_level) }} ({{ (customer.probability * 100).toFixed(1) }}%)
                  </el-tag>
              </div>
                  <div class="customer-option-details">
                合约: {{ getContractText(customer.contract) }} | 
                使用时长: {{ customer.tenure }}个月 | 
                月费用: ¥{{ customer.monthly_charges.toFixed(2) }}
                  </div>
              </div>
            </el-option>
              <template #dropdown>
                <div class="virtual-scroller-container">
                  <div v-if="customerLoading" style="padding: 10px; text-align: center;">
                    <el-icon class="is-loading"><i class="el-icon-loading"></i></el-icon> 加载中...
                  </div>
                  <template v-else>
                    <div class="virtual-scroller-content" ref="virtualScrollerContent">
                      <div 
                        v-for="customer in visibleCustomers" 
                        :key="`visible-${customer.customer_id}`"
                        class="virtual-scroller-item"
                        @click="selectCustomer(customer.customer_id)"
                      >
                        <div class="customer-option">
                          <div class="customer-option-header">
                            <span class="customer-id">{{ customer.customer_id }}</span>
                            <el-tag :type="getRiskTagType(customer.risk_level)" size="small">
                              {{ getRiskLevelText(customer.risk_level) }} ({{ (customer.probability * 100).toFixed(1) }}%)
                            </el-tag>
                          </div>
                          <div class="customer-option-details">
                            合约: {{ getContractText(customer.contract) }} | 
                            使用时长: {{ customer.tenure }}个月 | 
                            月费用: ¥{{ customer.monthly_charges.toFixed(2) }}
                          </div>
                        </div>
                      </div>
                      <div class="load-more" @click.stop="loadMoreCustomers">
                        加载更多客户
                      </div>
                    </div>
                  </template>
                </div>
              </template>
          </el-select>
          </div>
        </el-form-item>
        <el-form-item label="风险等级" prop="risk_level">
          <el-select v-model="createForm.risk_level" style="width: 100%">
            <el-option label="高风险" value="high"></el-option>
            <el-option label="中风险" value="medium"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="流失概率" prop="probability">
          <el-slider v-model="createForm.probability" :step="0.01" :min="0" :max="1" :format-tooltip="formatProbabilitySlider"></el-slider>
          <div style="margin-top: 5px; text-align: center;">{{ formatProbabilitySlider(createForm.probability) }}</div>
        </el-form-item>
        <el-form-item label="主要因素" prop="main_factors">
          <el-input v-model="createForm.main_factors" type="textarea" rows="3" placeholder="输入导致客户可能流失的主要因素"></el-input>
        </el-form-item>
        <el-form-item label="负责人" prop="assignee">
          <el-select v-model="createForm.assignee" clearable placeholder="选择负责人" style="width: 100%">
            <el-option 
              v-for="user in userList" 
              :key="user.id" 
              :label="user.full_name || user.username" 
              :value="user.id"
            >
              <div class="user-option">
                <div class="user-name">{{ user.full_name || user.username }}</div>
                <div class="user-info">
                  <span>{{ user.role_display || user.role }}</span>
                  <span v-if="user.department">· {{ user.department }}</span>
                </div>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitCreateForm" :loading="createLoading">创建</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getAlertList,
  createAlert as createAlertApi,
  processAlert as processAlertApi,
  closeAlert as closeAlertApi,
  batchProcessAlerts as batchProcessAlertsApi,
  getRetentionPlans,
  getAlertStatistics
} from '@/api/modules/alert'
import { getHighRiskCustomers } from '@/api/modules/customer'
import { getUserList } from '@/api/modules/user'
import { debounce } from 'lodash-es'

const router = useRouter()

// 加载状态
const loading = ref(false)
const processLoading = ref(false)
const createLoading = ref(false)

// 表格引用
const alertTable = ref(null)
const createFormRef = ref(null)

// 筛选表单数据
const filterForm = reactive({
  customerId: '',
  riskLevel: '',
  status: '',
  timeRange: [],
  assignee: ''
})

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 统计数据
const statistics = reactive({
  totalAlerts: 0,
  pendingAlerts: 0,
  processingAlerts: 0,
  completedAlerts: 0
})

// 预警列表
const alertList = ref([])

// 选中的行
const selectedRows = ref([])

// 当前操作的预警
const currentAlert = reactive({})

// 对话框控制
const processDialogVisible = ref(false)
const retentionDialogVisible = ref(false)
const createDialogVisible = ref(false)

// 处理表单数据
const processForm = reactive({
  customerId: '',
  riskLevel: '',
  riskLevelDisplay: '',
  assignee: '',
  actions: [],
  remarks: '',
  expectedCompletionTime: '',
  retained: false
})

// 创建预警表单数据
const createForm = reactive({
  customer_id: '',
  risk_level: 'high',
  probability: 0.7,
  main_factors: '',
  assignee: ''
})

// 创建表单验证规则
const createFormRules = {
  customer_id: [{ required: true, message: '请选择客户', trigger: 'change' }],
  risk_level: [{ required: true, message: '请选择风险等级', trigger: 'change' }],
  probability: [{ required: true, message: '请设置流失概率', trigger: 'change' }],
  main_factors: [{ required: true, message: '请输入主要风险因素', trigger: 'blur' }]
}

// 当前挽留方案
const currentRetentionPlan = ref(null)

// 高风险客户列表
const highRiskCustomers = ref([])

// 用户列表（用于选择负责人）
const userList = ref([])

// 客户数据相关
const customerSearchQuery = ref('')
const customerLoading = ref(false)
const customerPage = ref(1)
const customerPageSize = ref(50)
const filteredCustomers = ref([])
const customerCache = ref({}) // 客户数据缓存

// 创建大量数据时的虚拟滚动相关
const virtualScrollerContent = ref(null)
const virtualScrollOffset = ref(0)
const virtualItemHeight = 60 // 每项的估计高度
const visibleCount = ref(10) // 可见项数量

// 计算可见的客户列表
const visibleCustomers = computed(() => {
  const startIndex = Math.max(0, Math.floor(virtualScrollOffset.value / virtualItemHeight))
  const endIndex = Math.min(filteredCustomers.value.length, startIndex + visibleCount.value)
  return filteredCustomers.value.slice(startIndex, endIndex)
})

// 选择客户
const selectCustomer = (customerId) => {
  createForm.customer_id = customerId
  handleCustomerSelect(customerId)
}

// 监听虚拟滚动
const handleVirtualScroll = () => {
  if (virtualScrollerContent.value) {
    virtualScrollOffset.value = virtualScrollerContent.value.scrollTop
    
    // 如果滚动到底部，加载更多
    const { scrollTop, scrollHeight, clientHeight } = virtualScrollerContent.value
    if (scrollHeight - scrollTop - clientHeight < 100 && !customerLoading.value) {
      loadMoreCustomers()
    }
  }
}

// 在下拉菜单打开时设置滚动监听
const setupVirtualScroller = () => {
  setTimeout(() => {
    const dropdownContent = document.querySelector('.virtual-scroller-content')
    if (dropdownContent) {
      dropdownContent.addEventListener('scroll', handleVirtualScroll)
      
      // 计算可见项数量
      visibleCount.value = Math.ceil(dropdownContent.clientHeight / virtualItemHeight) + 5 // 多渲染5个以确保流畅
    }
  }, 300)
}

// 格式化概率滑块
const formatProbabilitySlider = (val) => {
  return `${(val * 100).toFixed(1)}%`
}

// 获取风险等级文本
const getRiskLevelText = (level) => {
  const map = {
    'high': '高风险',
    'medium': '中风险',
    'low': '低风险'
  }
  return map[level] || level
}

// 获取风险等级标签类型
const getRiskTagType = (level) => {
  const map = {
    'high': 'danger',
    'medium': 'warning',
    'low': 'info'
  }
  return map[level] || ''
}

// 获取合约类型文本
const getContractText = (contract) => {
  const map = {
    'Month-to-month': '月付',
    'One year': '一年',
    'Two year': '两年'
  }
  return map[contract] || contract
}

// 防抖函数
const debounceCustomerSearch = debounce(() => {
  remoteCustomerSearch(customerSearchQuery.value)
}, 300)

// 远程搜索客户
const remoteCustomerSearch = async (query) => {
  if (query) {
    // 检查缓存中是否已有该查询结果
    if (customerCache.value[query]) {
      filteredCustomers.value = customerCache.value[query]
      return
    }
    
    customerLoading.value = true
    try {
      const response = await getHighRiskCustomers({
        query: query,
        page: 1,
        page_size: 20
      })
      if (response.success) {
        const results = response.results || []
        filteredCustomers.value = results
        // 更新缓存
        customerCache.value[query] = results
      } else {
        ElMessage.warning('搜索客户列表失败: ' + (response.message || '未知错误'))
      }
    } catch (error) {
      console.error('搜索客户列表错误:', error)
    } finally {
      customerLoading.value = false
    }
  } else {
    // 如果查询为空，使用现有数据
    filterCustomersByRisk()
  }
}

// 根据风险等级过滤客户
const filterCustomersByRisk = () => {
  // 默认显示高风险客户，先处理少量数据加速显示
  filteredCustomers.value = highRiskCustomers.value
    .filter(customer => customer.risk_level === 'high')
    .slice(0, 20)
    
  // 延迟加载中等风险客户
  setTimeout(() => {
    filteredCustomers.value = highRiskCustomers.value
      .filter(customer => 
        customer.risk_level === 'high' || 
        (customer.risk_level === 'medium' && customer.probability > 0.5)
      )
      .slice(0, customerPageSize.value)
  }, 100)
}

// 客户列表本地过滤
const filterCustomers = (query) => {
  if (query) {
    filteredCustomers.value = highRiskCustomers.value.filter(customer => 
      customer.customer_id.toString().includes(query)
    ).slice(0, customerPageSize.value)
  } else {
    filterCustomersByRisk()
    }
  return filteredCustomers.value
}

// 加载更多客户
const loadMoreCustomers = () => {
  customerPage.value++
  loadHighRiskCustomers(true)
    }
    
// 监听highRiskCustomers变化，更新filteredCustomers
watch(highRiskCustomers, () => {
  filterCustomersByRisk()
})

// 加载高风险客户数据
const loadHighRiskCustomers = async (append = false) => {
  try {
    customerLoading.value = true
    const response = await getHighRiskCustomers({
      page: customerPage.value,
      page_size: customerPageSize.value
    })
    
    if (response.success) {
      if (append) {
        highRiskCustomers.value = [...highRiskCustomers.value, ...(response.results || [])]
      } else {
      highRiskCustomers.value = response.results || []
      }
      // 初始过滤
      filterCustomersByRisk()
    } else {
      ElMessage.warning('加载高风险客户列表失败: ' + (response.message || '未知错误'))
    }
  } catch (error) {
    console.error('加载高风险客户列表错误:', error)
    ElMessage.error('加载高风险客户列表失败')
  } finally {
    customerLoading.value = false
  }
}

// 加载用户列表
const loadUserList = async () => {
  try {
    console.log('正在加载用户列表...')
    const response = await getUserList()
    console.log('用户列表API响应:', response)
    
    if (response.success) {
      // 从response.data中获取用户列表
      userList.value = response.data || []
      console.log('成功加载用户列表:', userList.value)
    } else {
      // 如果API调用失败，使用备用数据
      console.warn('用户列表API调用失败，使用备用数据')
      userList.value = [
        { id: 1, username: '系统管理员', full_name: '系统管理员', role: '管理员', role_display: '管理员', department: 'IT' },
        { id: 2, username: '客户经理', full_name: '客户经理', role: '客户经理', role_display: '客户经理', department: '销售' },
        { id: 3, username: '数据分析师', full_name: '数据分析师', role: '分析师', role_display: '分析师', department: '数据' }
      ]
    }
  } catch (error) {
    console.error('加载用户列表错误:', error)
    // 出错时使用备用数据
    userList.value = [
      { id: 1, username: '系统管理员', full_name: '系统管理员', role: '管理员', role_display: '管理员', department: 'IT' },
      { id: 2, username: '客户经理', full_name: '客户经理', role: '客户经理', role_display: '客户经理', department: '销售' },
      { id: 3, username: '数据分析师', full_name: '数据分析师', role: '分析师', role_display: '分析师', department: '数据' }
    ]
  }
}

// 对话框标题
const dialogTitle = computed(() => {
  return currentAlert.status === 'pending' ? '处理预警' : '完成预警'
})

// 格式化日期时间
const formatDateTime = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 获取预警列表
const fetchAlerts = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params = {
      page: pagination.currentPage,
      page_size: pagination.pageSize
    }
    
    // 添加筛选条件
    if (filterForm.customerId) params.customer_id = filterForm.customerId
    if (filterForm.riskLevel) params.risk_level = filterForm.riskLevel
    if (filterForm.status) params.status = filterForm.status
    if (filterForm.assignee) params.assignee = filterForm.assignee
    if (filterForm.timeRange && filterForm.timeRange.length === 2) {
      params.start_date = filterForm.timeRange[0]
      params.end_date = filterForm.timeRange[1]
    }
    
    const response = await getAlertList(params)
    
    if (response.success) {
      alertList.value = response.results || []
      pagination.total = response.count || 0
      
      // 更新统计信息
      if (response.statistics) {
        statistics.totalAlerts = response.statistics.total_alerts || 0
        statistics.pendingAlerts = response.statistics.pending_alerts || 0
        statistics.processingAlerts = response.statistics.processing_alerts || 0
        statistics.completedAlerts = response.statistics.completed_alerts || 0
      } else {
        // 兼容旧接口，使用返回的计数
      statistics.totalAlerts = response.count || 0
      statistics.pendingAlerts = response.pending_count || 0
      statistics.processingAlerts = response.processing_count || 0
      statistics.completedAlerts = response.completed_count || 0
      }
    } else {
      ElMessage.error(response.message || '获取预警列表失败')
    }
  } catch (error) {
    console.error('获取预警列表错误:', error)
    ElMessage.error('获取预警列表失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 获取预警统计信息
const fetchAlertStatistics = async () => {
  try {
    const response = await getAlertStatistics()
    if (response.success && response.statistics) {
      statistics.totalAlerts = response.statistics.total_alerts || 0
      statistics.pendingAlerts = response.statistics.pending_alerts || 0
      statistics.processingAlerts = response.statistics.processing_alerts || 0
      statistics.completedAlerts = response.statistics.completed_alerts || 0
    }
  } catch (error) {
    console.error('获取预警统计信息错误:', error)
  }
}

// 格式化处理措施
const formatActions = (actions) => {
  if (!actions) return '-'
  
  try {
    if (typeof actions === 'string') {
      const actionList = JSON.parse(actions)
      return actionList.join('，')
    } else if (Array.isArray(actions)) {
      return actions.join('，')
    }
    return actions.toString()
  } catch (e) {
    return actions
  }
}

// 刷新数据
const refreshAlerts = async () => {
  loading.value = true
  
  try {
    // 构建请求参数
    const params = {
      page: pagination.currentPage,
      page_size: pagination.pageSize,
      customer_id: filterForm.customerId || undefined,
      risk_level: filterForm.riskLevel || undefined,
      status: filterForm.status || undefined,
      assignee: filterForm.assignee || undefined
    }
    
    // 添加日期范围
    if (filterForm.timeRange && filterForm.timeRange.length === 2) {
      params.start_date = filterForm.timeRange[0]
      params.end_date = filterForm.timeRange[1]
    }
    
    // 调用API获取数据
    const response = await getAlertList(params)
    
    if (response.success) {
      // 设置列表数据
      alertList.value = response.results
      pagination.total = response.count
      
      // 更新统计信息
      if (response.statistics) {
        statistics.totalAlerts = response.statistics.total_alerts || 0
        statistics.pendingAlerts = response.statistics.pending_alerts || 0
        statistics.processingAlerts = response.statistics.processing_alerts || 0
        statistics.completedAlerts = response.statistics.completed_alerts || 0
      } else {
        // 兼容旧接口，使用返回的计数
        statistics.totalAlerts = response.count || 0
        statistics.pendingAlerts = response.pending_count || 0
        statistics.processingAlerts = response.processing_count || 0
        statistics.completedAlerts = response.completed_count || 0
      }
    } else {
      ElMessage.error(response.message || '获取预警列表失败')
    }
  } catch (error) {
    console.error('获取预警列表错误:', error)
    ElMessage.error('获取预警列表失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 重置筛选条件
const resetFilter = () => {
  Object.keys(filterForm).forEach(key => {
    filterForm[key] = key === 'timeRange' ? [] : ''
  })
  fetchAlerts()
}

// 应用筛选条件
const handleFilter = () => {
  pagination.currentPage = 1
  fetchAlerts()
}

// 选择行变更事件
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 页大小变更
const handleSizeChange = (size) => {
  pagination.pageSize = size
  fetchAlerts()
}

// 页码变更
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  fetchAlerts()
}

// 查看客户详情
const viewCustomerDetail = (row) => {
  router.push(`/customer/detail/${row.customer_id}`)
}

// 处理预警
const processAlert = async (row) => {
  // 确保先加载用户列表
  await loadUserList()
  
  // 复制当前预警数据
  Object.assign(currentAlert, row)
  
  // 初始化表单数据
  processForm.customerId = row.customer_id
  processForm.riskLevel = row.risk_level
  processForm.riskLevelDisplay = row.risk_level_display
  
  // 设置负责人为对应的用户ID
  processForm.assignee = row.assignee || ''  // 使用用户ID
  processForm.actions = []
  processForm.remarks = ''
  processForm.expectedCompletionTime = ''
  processForm.retained = false
  
  // 显示对话框
  processDialogVisible.value = true
  
  // 输出调试信息
  console.log('用户列表:', userList.value)
  console.log('当前设置的负责人:', processForm.assignee)
}

// 确认处理预警
const confirmProcess = async () => {
  if (!processForm.assignee) {
    ElMessage.warning('请选择负责人')
    return
  }
  
  if (processForm.actions.length === 0) {
    ElMessage.warning('请选择处理措施')
    return
  }
  
  processLoading.value = true
  
  try {
    // 准备请求数据 - 使用用户ID作为assignee
    const data = {
      assignee: processForm.assignee, // 直接使用用户ID
      actions: processForm.actions,
      remarks: processForm.remarks
    }
    
    // 添加特定字段
    if (currentAlert.status === 'pending') {
      data.expected_completion_time = processForm.expectedCompletionTime
    } else if (currentAlert.status === 'processing') {
      data.is_completed = true
      data.is_retained = processForm.retained
    }
    
    // 调用API处理预警
    const response = await processAlertApi(currentAlert.id, data)
    
    if (response.success) {
      // 提示成功
      ElMessage({
        message: currentAlert.status === 'pending' ? '已开始处理预警并通知负责人' : '已完成预警处理',
        type: 'success'
      })

      // 关闭对话框
      processDialogVisible.value = false

      // 刷新数据
      fetchAlerts()
      fetchAlertStatistics() // 刷新统计数据
    } else {
      ElMessage.error(response.message || '处理预警失败')
    }
  } catch (error) {
    console.error('处理预警错误:', error)
    
    // 检查是否是401或403错误（可能是token过期）
    if (error.response && (error.response.status === 401 || error.response.status === 403)) {
      ElMessage({
        message: '您的登录状态已过期，正在尝试自动续期...',
        type: 'warning'
      })
      
      // 延迟一会儿再重试，给token刷新一些时间
      setTimeout(() => {
        ElMessage.info('请重试处理预警操作')
        processLoading.value = false
      }, 2000)
    } else {
    ElMessage.error('处理预警失败: ' + (error.message || '未知错误'))
    processLoading.value = false
    }
  }
}

// 查看挽留方案
const viewRetentionPlan = async (row) => {
  try {
    const response = await getRetentionPlans(row.id)
    
    if (response.success && response.data && response.data.length > 0) {
      // 使用最新的挽留方案
      currentRetentionPlan.value = response.data[0]
      retentionDialogVisible.value = true
    } else {
      ElMessage.info('该预警暂无挽留方案')
    }
  } catch (error) {
    console.error('获取挽留方案错误:', error)
    ElMessage.error('获取挽留方案失败: ' + (error.message || '未知错误'))
  }
}

// 编辑挽留方案
const editRetentionPlan = () => {
  ElMessage({
    message: '挽留方案编辑功能将在后续版本中实现',
    type: 'info'
  })
}

// 关闭预警
const closeAlert = (row) => {
  ElMessageBox.confirm(`确定要关闭预警 ${row.customer_id} 吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await closeAlertApi(row.id)
      
      if (response.success) {
        ElMessage({
          message: '已关闭预警',
          type: 'success'
        })
        
        // 刷新数据
        fetchAlerts()
        fetchAlertStatistics() // 刷新统计数据
      } else {
        ElMessage.error(response.message || '关闭预警失败')
      }
    } catch (error) {
      console.error('关闭预警错误:', error)
      ElMessage.error('关闭预警失败: ' + (error.message || '未知错误'))
    }
  }).catch(() => {})
}

// 批量处理
const batchProcess = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条预警记录')
    return
  }
  
  const pendingAlerts = selectedRows.value.filter(row => row.status === 'pending')
  const processingAlerts = selectedRows.value.filter(row => row.status === 'processing')
  
  if (pendingAlerts.length === 0 && processingAlerts.length === 0) {
    ElMessage.warning('所选预警已完成或已关闭，无需处理')
    return
  }
  
  ElMessageBox.confirm(`确定要批量处理所选的 ${pendingAlerts.length + processingAlerts.length} 条预警吗？`, '确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info'
  }).then(async () => {
    try {
      // 准备请求数据
      const data = {
        alert_ids: selectedRows.value.map(row => row.id)
      }
      
      if (pendingAlerts.length > 0 && processingAlerts.length === 0) {
        data.action = 'start_processing'
      } else if (pendingAlerts.length === 0 && processingAlerts.length > 0) {
        data.action = 'complete'
      } else {
        // 混合状态，优先处理pending
        data.action = 'start_processing'
        data.alert_ids = pendingAlerts.map(row => row.id)
      }
      
      const response = await batchProcessAlertsApi(data)
      
      if (response.success) {
        ElMessage({
          message: `已批量处理 ${response.processed_count || 0} 条预警`,
          type: 'success'
        })
        
        // 如果还有processing状态的预警，继续处理
        if (pendingAlerts.length > 0 && processingAlerts.length > 0) {
          const processingData = {
            alert_ids: processingAlerts.map(row => row.id),
            action: 'complete'
          }
          
          await batchProcessAlertsApi(processingData)
        }
        
        // 清除选择
        alertTable.value?.clearSelection()
        
        // 刷新数据
        fetchAlerts()
        fetchAlertStatistics() // 刷新统计数据
      } else {
        ElMessage.error(response.message || '批量处理预警失败')
      }
    } catch (error) {
      console.error('批量处理预警错误:', error)
      ElMessage.error('批量处理预警失败: ' + (error.message || '未知错误'))
    }
  }).catch(() => {})
}

// 创建预警
const showCreateAlertDialog = async () => {
  // 确保先加载用户列表
  await loadUserList()
  
  createDialogVisible.value = true
  
  // 重置表单
  if (createFormRef.value) {
    createFormRef.value.resetFields()
  }
  
  // 设置默认值
  createForm.risk_level = 'high'
  createForm.probability = 0.7
  
  // 重置客户筛选状态
  customerSearchQuery.value = ''
  customerPage.value = 1
  
  // 加载高风险客户列表
  loadHighRiskCustomers()
  
  // 输出调试信息
  console.log('创建预警 - 用户列表:', userList.value)
}

// 提交创建表单
const submitCreateForm = async () => {
  if (!createFormRef.value) return
  
  try {
    // 验证前禁用按钮，避免重复点击
    if (createLoading.value) return
      createLoading.value = true
      
    // 使用Promise方式进行表单验证，提高性能
    const valid = await createFormRef.value.validate()
      .catch(err => {
        console.error('表单验证错误:', err)
        return false
      })
    
    if (valid) {
        const data = { ...createForm }
        
      // 直接使用现有数据，不做额外处理
        const response = await createAlertApi(data)
        
        if (response.success) {
          ElMessage({
            message: '预警创建成功',
            type: 'success'
          })
          
          // 关闭对话框
          createDialogVisible.value = false
          
        // 异步刷新数据
        setTimeout(() => {
          fetchAlerts()
          fetchAlertStatistics() // 刷新统计数据
          // 只在后台异步刷新客户列表，不阻塞UI
          loadHighRiskCustomers()
        }, 100)
        } else {
          ElMessage.error(response.message || '创建预警失败')
      }
        }
      } catch (error) {
        console.error('创建预警错误:', error)
        ElMessage.error('创建预警失败: ' + (error.message || '未知错误'))
      } finally {
        createLoading.value = false
      }
    }

// 处理客户选择 - 性能优化版本
const handleCustomerSelect = (customerId) => {
  // 首先从filteredCustomers中查找，避免全量数据扫描
  let selectedCustomer = filteredCustomers.value.find(c => c.customer_id === customerId)
  
  // 如果没找到，再从全量数据中查找
  if (!selectedCustomer) {
    selectedCustomer = highRiskCustomers.value.find(c => c.customer_id === customerId)
  }
  
  if (selectedCustomer) {
    // 使用批量赋值，减少重绘次数
    Object.assign(createForm, {
      risk_level: selectedCustomer.risk_level,
      probability: selectedCustomer.probability
    })
    
    // 异步生成主要风险因素，不阻塞UI
    setTimeout(() => {
      const factors = []
      
      if (selectedCustomer.tenure < 12) {
        factors.push("新客户（使用时长少于12个月）")
      }
      
      if (selectedCustomer.monthly_charges > 80) {
        factors.push("月费用较高")
      }
      
      if (selectedCustomer.contract === 'Month-to-month') {
        factors.push("按月合同，无长期约束")
      }
      
      createForm.main_factors = factors.join('，')
    }, 0)
  }
}

// 生命周期钩子
onMounted(async () => {
  fetchAlerts()
  fetchAlertStatistics() // 初始加载统计信息
  
  // 立即加载用户列表，确保数据可用
  await loadUserList() 
  
  loadHighRiskCustomers() // 初始加载高风险客户列表
  
  // 监听select展开事件以初始化虚拟滚动
  document.addEventListener('click', (e) => {
    if (e.target.closest('.el-select')) {
      setupVirtualScroller()
    }
  })
})
</script>

<style lang="scss" scoped>
.alert-management-container {
  padding: 20px;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    align-items: center;
    
    .page-title {
      font-size: 22px;
      font-weight: bold;
    }
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .filter-card {
    margin-bottom: 20px;
  }
  
  .stats-card-container {
    margin-bottom: 20px;
    
    .stats-card {
      height: 100px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 20px;
      
      .stats-card-content {
        text-align: center;
        
        .stats-value {
          font-size: 28px;
          font-weight: bold;
          margin-bottom: 5px;
        }
        
        .stats-label {
          font-size: 14px;
          color: #909399;
        }
      }
      
      &.stats-pending {
        .stats-value {
          color: #409EFF;
        }
      }
      
      &.stats-processing {
        .stats-value {
          color: #E6A23C;
        }
      }
      
      &.stats-completed {
        .stats-value {
          color: #67C23A;
        }
      }
    }
  }
  
  .alert-list-card {
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
  
  .retention-result {
    margin-top: 20px;
    background-color: #f8f9fa;
    border-radius: 4px;
    padding: 15px;
    
    h4 {
      margin-top: 0;
      margin-bottom: 15px;
      color: #303133;
    }
    
    .result-item {
      display: flex;
      margin-bottom: 10px;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .result-label {
        width: 120px;
        color: #606266;
      }
      
      .result-value {
        font-weight: bold;
        color: #409EFF;
      }
    }
  }

  .customer-select-container {
    width: 100%;
    
    .customer-search-bar {
      margin-bottom: 5px;
    }
  }

  :deep(.virtual-scroller-container) {
    height: 300px;
    overflow: hidden;
    position: relative;
    
    .virtual-scroller-content {
      height: 100%;
      overflow-y: auto;
      overflow-x: hidden;
    }
    
    .virtual-scroller-item {
      cursor: pointer;
      
      &:hover {
        background-color: #f5f7fa;
      }
    }
  }

  :deep(.customer-select-dropdown) {
    .el-select-dropdown__item {
      padding: 0;
      
      &.selected {
        background-color: #f5f7fa;
      }
    }
  }
  
  .customer-option {
    padding: 8px 15px;
    
    .customer-option-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 3px;
      
      .customer-id {
        font-weight: 500;
      }
    }
    
    .customer-option-details {
      font-size: 12px;
      color: #606266;
    }
    
    :deep(.load-more) {
      text-align: center;
      padding: 10px 0;
      color: #409EFF;
      cursor: pointer;
      
      &:hover {
        background-color: #f5f7fa;
      }
    }
  }

  .user-option {
    padding: 5px 0;
    
    .user-name {
      font-size: 14px;
      font-weight: 500;
    }
    
    .user-info {
      font-size: 12px;
      color: #909399;
    }
  }
}
</style> 